/**
 * 测试新浪API股票数据与东方财富分类数据的匹配性
 * 验证股票代码格式是否一致，能否正确匹配
 */

import fetch from 'node-fetch';

// 模拟新浪API数据格式
async function getSinaStockData() {
  try {
    // 获取几只A股样本数据
    const symbols = ['sh600519', 'sz000001', 'sh600036', 'sz300059']; // 茅台、平安、招商、东方财富
    const url = `https://hq.sinajs.cn/list=${symbols.join(',')}`;
    
    console.log('📡 请求新浪API:', url);
    
    const response = await fetch(url, {
      headers: {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
        'Referer': 'https://finance.sina.com.cn'
      }
    });

    if (!response.ok) {
      throw new Error(`HTTP Error: ${response.status}`);
    }

    const text = await response.text();
    console.log('🔍 新浪API原始响应:');
    console.log(text.substring(0, 500) + '...\n');

    // 解析股票数据
    const lines = text.split('\n').filter(line => line.trim());
    const stocks = [];
    
    lines.forEach((line, index) => {
      const match = line.match(/var hq_str_(\w+)="([^"]*)"/);
      if (match) {
        const symbol = match[1];
        const data = match[2].split(',');
        
        // 从symbol解析市场和代码
        let market = '';
        let code = '';
        if (symbol.startsWith('sh')) {
          market = 'SH';
          code = symbol.substring(2);
        } else if (symbol.startsWith('sz')) {
          market = 'SZ';  
          code = symbol.substring(2);
        }
        
        stocks.push({
          sinaSymbol: symbol,          // sh600519
          market: market,              // SH
          stockCode: code,             // 600519
          stockName: data[0] || '',    // 贵州茅台
          currentPrice: parseFloat(data[3]) || 0
        });
      }
    });

    return stocks;
  } catch (error) {
    console.error('❌ 获取新浪股票数据失败:', error.message);
    return [];
  }
}

// 模拟东方财富概念板块API数据格式
async function getEastmoneyConceptData() {
  try {
    // 模拟东方财富概念板块数据（实际需要真实API）
    console.log('📈 模拟东方财富概念板块数据...');
    
    // 这里模拟一些概念板块数据
    const conceptData = {
      '白酒概念': {
        conceptCode: 'BK0896',
        conceptName: '白酒概念',
        stocks: [
          { code: '600519', name: '贵州茅台', market: 'SH' },
          { code: '000858', name: '五粮液', market: 'SZ' },
          { code: '000596', name: '古井贡酒', market: 'SZ' }
        ]
      },
      '银行': {
        conceptCode: 'BK0475', 
        conceptName: '银行',
        stocks: [
          { code: '000001', name: '平安银行', market: 'SZ' },
          { code: '600036', name: '招商银行', market: 'SH' },
          { code: '600000', name: '浦发银行', market: 'SH' }
        ]
      },
      '互联网金融': {
        conceptCode: 'BK0650',
        conceptName: '互联网金融',
        stocks: [
          { code: '300059', name: '东方财富', market: 'SZ' },
          { code: '002736', name: '国信证券', market: 'SZ' }
        ]
      }
    };
    
    return conceptData;
  } catch (error) {
    console.error('❌ 获取东方财富概念数据失败:', error.message);
    return {};
  }
}

// 测试数据匹配性
async function testDataMatching() {
  console.log('🧪 开始测试数据匹配性...\n');
  
  // 获取新浪股票数据
  console.log('=== 步骤1: 获取新浪股票数据 ===');
  const sinaStocks = await getSinaStockData();
  
  if (sinaStocks.length === 0) {
    console.log('⚠️ 新浪API可能被限制，使用模拟数据继续测试...');
    // 使用模拟数据
    const mockSinaStocks = [
      { sinaSymbol: 'sh600519', market: 'SH', stockCode: '600519', stockName: '贵州茅台', currentPrice: 1745.50 },
      { sinaSymbol: 'sz000001', market: 'SZ', stockCode: '000001', stockName: '平安银行', currentPrice: 8.57 },
      { sinaSymbol: 'sh600036', market: 'SH', stockCode: '600036', stockName: '招商银行', currentPrice: 26.89 },
      { sinaSymbol: 'sz300059', market: 'SZ', stockCode: '300059', stockName: '东方财富', currentPrice: 18.25 }
    ];
    sinaStocks.push(...mockSinaStocks);
  }
  
  console.log('📊 新浪股票数据解析结果:');
  sinaStocks.forEach(stock => {
    console.log(`  ${stock.sinaSymbol} -> ${stock.market}:${stock.stockCode} ${stock.stockName} ¥${stock.currentPrice}`);
  });
  
  // 获取东方财富概念数据
  console.log('\n=== 步骤2: 获取东方财富概念板块数据 ===');
  const conceptData = await getEastmoneyConceptData();
  
  console.log('📈 东方财富概念板块:');
  Object.keys(conceptData).forEach(conceptName => {
    const concept = conceptData[conceptName];
    console.log(`  ${conceptName} (${concept.conceptCode}):`);
    concept.stocks.forEach(stock => {
      console.log(`    ${stock.market}:${stock.code} ${stock.name}`);
    });
  });
  
  // 进行匹配测试
  console.log('\n=== 步骤3: 数据匹配性测试 ===');
  let matchedCount = 0;
  let totalConceptStocks = 0;
  
  Object.keys(conceptData).forEach(conceptName => {
    const concept = conceptData[conceptName];
    console.log(`\n🔍 测试概念: ${conceptName}`);
    
    concept.stocks.forEach(conceptStock => {
      totalConceptStocks++;
      const matchingStock = sinaStocks.find(sinaStock => 
        sinaStock.market === conceptStock.market && 
        sinaStock.stockCode === conceptStock.code
      );
      
      if (matchingStock) {
        matchedCount++;
        console.log(`  ✅ 匹配成功: ${conceptStock.market}:${conceptStock.code} ${conceptStock.name}`);
        console.log(`     新浪数据: ${matchingStock.sinaSymbol} ${matchingStock.stockName} ¥${matchingStock.currentPrice}`);
      } else {
        console.log(`  ❌ 匹配失败: ${conceptStock.market}:${conceptStock.code} ${conceptStock.name}`);
      }
    });
  });
  
  // 输出匹配统计
  console.log('\n=== 匹配统计结果 ===');
  console.log(`📊 总概念股数量: ${totalConceptStocks}`);
  console.log(`✅ 匹配成功数量: ${matchedCount}`);
  console.log(`❌ 匹配失败数量: ${totalConceptStocks - matchedCount}`);
  console.log(`📈 匹配成功率: ${((matchedCount / totalConceptStocks) * 100).toFixed(1)}%`);
  
  // 分析匹配问题
  console.log('\n=== 匹配性分析 ===');
  if (matchedCount === totalConceptStocks) {
    console.log('🎉 完美匹配！新浪API数据与东方财富概念数据完全兼容');
  } else if (matchedCount > totalConceptStocks * 0.8) {
    console.log('✅ 匹配度良好，可以使用混合数据源方案');
    console.log('💡 建议：对未匹配的股票进行单独处理或过滤');
  } else {
    console.log('⚠️ 匹配度较低，建议统一数据源或建立映射表');
  }
  
  // 输出代码格式分析
  console.log('\n=== 代码格式分析 ===');
  console.log('新浪API格式: sh600519, sz000001 (小写前缀+代码)');
  console.log('东方财富格式: SH:600519, SZ:000001 (大写市场+代码)');
  console.log('转换逻辑: 可以通过简单的字符串处理实现互转');
  
  return {
    totalStocks: totalConceptStocks,
    matchedStocks: matchedCount,
    matchRate: (matchedCount / totalConceptStocks) * 100,
    isCompatible: matchedCount > totalConceptStocks * 0.8
  };
}

// 运行测试
async function runTest() {
  try {
    console.log('🚀 股票数据源匹配性测试开始...\n');
    
    const result = await testDataMatching();
    
    console.log('\n✨ 测试完成！');
    console.log(`结果: ${result.isCompatible ? '✅ 兼容' : '❌ 不兼容'}`);
    
    if (result.isCompatible) {
      console.log('\n📋 推荐实施方案:');
      console.log('1. 保持新浪API作为主要数据源（实时行情）');
      console.log('2. 使用东方财富API补充概念板块分类');
      console.log('3. 建立代码格式转换器：sh600519 <-> SH:600519');
      console.log('4. 定期同步概念板块成分股信息');
    } else {
      console.log('\n⚠️ 建议修正方案:');
      console.log('1. 选择单一数据源确保一致性');
      console.log('2. 或建立完整的股票代码映射表');
      console.log('3. 增加数据校验和错误处理机制');
    }
    
  } catch (error) {
    console.error('💥 测试过程中发生错误:', error);
  }
}

// 执行测试
runTest().catch(console.error);